package com.dai.zhenfujin;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.dai.zhenfujin.Constants.Constants;
import com.dai.zhenfujin.base.BaseActivity;
import com.dai.zhenfujin.bean.ResBdBean;
import com.dai.zhenfujin.http.CallBack;
import com.dai.zhenfujin.http.HttpClient;
import com.dai.zhenfujin.utils.SPUtils;
import com.dai.zhenfujin.utils.UIUtils;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.exceptions.HyphenateException;

import java.util.HashMap;
import java.util.Map;

/**
 * 手机快捷登录页面
 */
public class RegisterActivity extends BaseActivity implements View.OnClickListener {
    private EditText etNumber, etSms, register_img;

    private TextView tvVerification, register_login, tv_login, register_cancel;
    private Button button;
    private ImageView register_show_img;
    private String verifyId;
    private VerificationCodeCountTimer verificationCodeCountTimer;
    private String ver_env;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        etNumber = findViewById(R.id.register_number);
        etSms = findViewById(R.id.register_sms);
        tvVerification = findViewById(R.id.register_verification);
        button = findViewById(R.id.register_button);
        register_login = findViewById(R.id.register_login);
        register_cancel = findViewById(R.id.register_cancel);
        tv_login = findViewById(R.id.tv_login);
        register_show_img = findViewById(R.id.register_show_img);
        register_img = findViewById(R.id.register_img);

        button.setOnClickListener(this);
        //验证码
        tvVerification.setOnClickListener(this);
        //注册
        register_login.setOnClickListener(this);

        tv_login.setOnClickListener(this);
        register_cancel.setOnClickListener(this);
        register_show_img.setOnClickListener(this);
        verificationCodeCountTimer = new VerificationCodeCountTimer(61100, 1000);

        //得到图形验证码
        getVerify();
    }

    private void getVerify() {
        Map<String, Object> params = new HashMap<>();
        Map<String, String> params2 = new HashMap<>();
        params.put("req_bd", params2);
        HttpClient.post(this, Constants.CODE_URL, params, new CallBack<ResBdBean>() {
            @Override
            public void onSuccess(ResBdBean resultBean) {
                verifyId = resultBean.verifyId;
                ver_env = resultBean.ver_env;
                Glide.with(RegisterActivity.this).load(resultBean.url).into(register_show_img);
                // etSms.setText(code);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //登录
            case R.id.register_button:
                login();
                break;
            case R.id.register_cancel:
                finish();
                break;
            case R.id.register_verification:
                getCode();
                break;
            case R.id.register_show_img:  //图形验证码
                getVerify();
                break;
            case R.id.register_login: //注册
                startActivity(new Intent(this, LoginActivity.class));
                break;
            case R.id.tv_login: //帐号密码登录
                startActivity(new Intent(this, AccountPasswordActivity.class));
                finish();
                break;
        }
    }

    /*
         快速登录
     */
    private void login() {
        if (!UIUtils.isMobileNO(etNumber.getText().toString().trim())) {
            UIUtils.showToastSafe("请输入手机号码");
            return;
        }

        if (TextUtils.isEmpty(register_img.getText().toString().trim())) {
            UIUtils.showToastSafe("请输入图形验证码");
            return;
        }
        if (TextUtils.isEmpty(etSms.getText().toString().trim())) {
            UIUtils.showToastSafe("请输入验证码");
            return;
        }
        new Thread() {
            @Override
            public void run() {
                try {
                    //环信注册
                    EMClient.getInstance().createAccount(etNumber.getText().toString().trim() + "", "zfj123");
                } catch (HyphenateException e) {
                    e.printStackTrace();
                }
                super.run();
            }
        }.start();


        Map<String, Object> params = new HashMap<>();
        Map<String, String> params2 = new HashMap<>();

        params2.put("mobile", etNumber.getText().toString().trim());
        params2.put("code", etSms.getText().toString().trim());
        params.put("req_bd", params2);

        HttpClient.post(this, Constants.FASTLOGIN, params, new CallBack<ResBdBean>() {
            @Override
            public void onSuccess(ResBdBean resultBean) {
                SPUtils.put(RegisterActivity.this, "welcome", true);
                SPUtils.put(RegisterActivity.this, Constants.TOKEN, resultBean.getAccess_token());
                // EMClient.getInstance().groupManager().loadAllGroups();
                EMClient.getInstance().chatManager().loadAllConversations();
                EMClient.getInstance().login(etNumber.getText().toString().trim(), "zfj123", new EMCallBack() {//回调
                    @Override
                    public void onSuccess() {
                        Log.d("main", "登录聊天服务器成功");

                        startActivity(new Intent(RegisterActivity.this, MainActivity.class).putExtra("showRed",0));
                        finish();
                    }

                    @Override
                    public void onProgress(int progress, String status) {

                    }

                    @Override
                    public void onError(int code, String message) {
                        Log.d("main", "登录聊天服务器失败！");
                    }
                });
            }
        });
    }

    /**
     * 获取验证码
     */
    private void getCode() {
        if (!UIUtils.isMobileNO(etNumber.getText().toString().trim())) {
            UIUtils.showToastSafe("请输入手机号码");
            return;
        }

        if (TextUtils.isEmpty(register_img.getText().toString().trim())) {
            UIUtils.showToastSafe("请输入图形验证码");
            return;
        }
     //   verificationCodeCountTimer.start();
        Map<String, Object> params = new HashMap<>();
        Map<String, String> params2 = new HashMap<>();

        params2.put("mobile", etNumber.getText().toString());
        params2.put("type", "4");
        params2.put("verifyId", verifyId);
        params2.put("ver_env", ver_env);
        params2.put("verifyCode", register_img.getText().toString().trim());

        params.put("req_bd", params2);

        HttpClient.post(this, Constants.GETCODE, params, new CallBack<ResBdBean>() {
            @Override
            public void onSuccess(ResBdBean resultBean) {
                if (resultBean.getSms_code().equals("true")){
                    UIUtils.showToastSafe("验证码已发送");
                    verificationCodeCountTimer.start();
                }else {
                    UIUtils.showToastSafe("获取过于频繁，请稍后一分钟后在试");
                }
            }
        });
    }


    class VerificationCodeCountTimer extends CountDownTimer {

        private VerificationCodeCountTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            int time = (int) (Math.round((double) millisUntilFinished / 1000) - 1);
            tvVerification.setTextColor(getResources().getColor(R.color.btn_blue_normal));
            tvVerification.setText(time + "s");
        }

        @Override
        public void onFinish() {
            tvVerification.setText("获取验证码");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (verificationCodeCountTimer != null) {
            verificationCodeCountTimer.cancel();
        }
    }
}
